/*
 * JSONConverter.java
 *
 * Created on April 17, 2007, 1:34 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.voidness.twittava.conversion.converters;

import java.util.ArrayList;
import java.util.Collection;
import org.voidness.twittava.conversion.json.JSONArray;
import org.voidness.twittava.conversion.json.JSONException;
import org.voidness.twittava.conversion.json.JSONObject;
import org.voidness.twittava.domain.Status;
import org.voidness.twittava.domain.StatusUser;

/**
 *
 * @author void
 */
public class JSONConverter implements Converter {
    
    private Status statusFromJSONObject(JSONObject obj) throws Exception {
        Status status = new Status();
        status.setId(obj.getInt("id"));
        status.setText(obj.getString("text"));
        status.setCreationDate(obj.getString("created_at"));
        return status;
    }
    
    private StatusUser userFromJSONObject(JSONObject obj) throws Exception {
        StatusUser user = new StatusUser();
        user.setId(obj.getInt("id"));
        user.setName(obj.getString("name"));
        user.setScreenName(obj.getString("screen_name"));
        user.setDescription(obj.getString("description"));
        user.setLocation(obj.getString("location"));
        user.setProfileImageUrl(obj.getString("profile_image_url"));
        user.setUrl(obj.getString("url"));
        return user;
    }
    
    public Collection<Status> convertTimeline(String data) throws Exception {
        Collection<Status> allStatuses = new ArrayList<Status>();
        JSONArray array = new JSONArray(data);
        for (int i=0; i<array.length(); i++) {
            JSONObject statusPost = array.getJSONObject(i);
            JSONObject postUser = statusPost.getJSONObject("user");
            Status status = statusFromJSONObject(statusPost);
            status.setUser(userFromJSONObject(postUser));
            System.out.println(statusPost);
            allStatuses.add(status);
        }
        return allStatuses;
    }
    
    public Status convertStatus(String data) throws Exception {
        JSONObject statusPost = new JSONObject(data);
        JSONObject postUser = statusPost.getJSONObject("user");
        Status status = statusFromJSONObject(statusPost);
        status.setUser(userFromJSONObject(postUser));
        return status;
    }
    
}
